<template>
  <div id="details">
    <div class="page-header">
      <div class="title">
        <p>{{ pDetail.productName }}</p>
      </div>
    </div>
    <div class="main">
      <div class="product-area">
        <div class="block">
          <el-carousel height="560px" v-if="imgs.length > 1">
            <el-carousel-item v-for="(item, idx) in imgs" :key="'img' + idx">
              <img
                style="height:560px;"
                :src="baseURL + item.serverPath"
                alt="产品详情"
              />
            </el-carousel-item>
          </el-carousel>
          <div v-if="imgs.length == 1">
            <img
              style="height:560px;"
              :src="baseURL + imgs[0].serverPath"
              alt="产品详情"
            />
          </div>
        </div>

        <div class="content">
          <div class="price">
            <h1 class="name">{{ pDetail.productName }}</h1>
            <p class="intro">{{ pDetail.description }}</p>
          </div>
          <div class="pro-storage">
            <span class="counter-label">数量:</span>
            <el-input-number
              v-model="counter"
              :max="pDetail.inventory"
              :min="0"
            ></el-input-number>
            <span class="counter-message" v-if="pDetail.inventory > 0"
              >当前库存{{ pDetail.inventory || 0 }}件</span
            >
            <span class="counter-message" v-else>该商品暂时缺货</span>
          </div>
          <div class="pro-list">
            <span class="pro-name">{{ pDetail.productName }}</span>
            <span class="pro-price">
              现货价:
              <span class="pro-price-num"
                >{{
                  pDetail.discountPrice > 0
                    ? pDetail.discountPrice
                    : pDetail.price
                }}元</span
              >
              <span class="pro-del" v-if="pDetail.discountPrice > 0"
                >{{ pDetail.price }}元</span
              >
            </span>
            <p class="price-sum">总计 : {{ totalText }}</p>
          </div>

          <div class="button">
            <el-button
              class="shop-cart"
              @click="addShoppingCart"
              :loading="saving"
              >加入购物车</el-button
            >
            <el-button class="like" type="primary" @click="handleSettle"
              >立即购买</el-button
            >
          </div>
          <div class="pro-policy">
            <ul>
              <li><i class="el-icon-circle-check"></i> 7天无理由退货</li>
              <li><i class="el-icon-circle-check"></i> 7天价格保护</li>
              <li><i class="el-icon-circle-check"></i> 消费者保护</li>
            </ul>
          </div>
        </div>
      </div>
      <el-tabs
        type="border-card"
        class="product-tabs"
        v-model="activeTab"
        @tab-click="handleTabChange"
      >
        <el-tab-pane name="detail" label="商品详情">
          <div
            v-if="pDetail.content"
            class="desc-detail"
            v-html="pDetail.content"
          ></div>
          <div v-else class="desc-empty">
            <h2 align="center">该商品暂未发布介绍</h2>
          </div>
        </el-tab-pane>
        <el-tab-pane name="comment" label="商品评论">
          <div class="comment-area">
            <template v-if="comment.list.length > 0">
              <div
                class="comment-item"
                v-for="(item, idx) in comment.list"
                :key="'comment' + idx"
              >
                <div class="comment-user">
                  <template v-if="item.user">
                    <img
                      :src="baseURL + item.user.avatar"
                      class="comment-user--avatar"
                      alt="暂时无法显示用户头像"
                    />
                    <span class="comment-user--username">{{
                      item.user.username
                    }}</span>
                  </template>
                </div>
                <div class="comment-content">
                  <el-rate
                    class="comment-content--rate"
                    :value="item.rate"
                    :colors="colors"
                    disabled
                  ></el-rate>
                  <span class="comment-content--desc">{{ item.content }}</span>
                  <span class="comment-content--time">{{
                    item.createTime
                  }}</span>
                </div>
              </div>
              <div class="comment-pagination" v-if="comment.list.length > 0">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :page-size="comment.pageSize"
                  :total="comment.total"
                  @current-change="handleCurrentChange"
                ></el-pagination>
              </div>
            </template>
            <div class="empty-comment" v-else>
              <h2 align="center">该商品暂时还没有评论</h2>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="back-to-top" @click="back2Top">
      <span class="el-icon-upload2"></span>
    </div>
  </div>
</template>
<script>
import { baseURL } from "@/config";
import { productApi, cartApi, commentApi } from "@/api";
import { mapActions } from "vuex";
export default {
  data() {
    return {
      colors: ["#49af4f", "#49af4f", "green"],
      productId: null, // 商品id
      pDetail: {
        price: 0,
        productName: "",
        descritption: ""
      }, // 商品详细信息
      imgs: [], // 商品图片
      counter: 0,
      comment: {
        list: [],
        total: 0,
        pageSize: 15
      },
      timer: null,
      saving: false,
      activeTab: "detail",
      lastTab: null
    };
  },
  computed: {
    totalText() {
      var price =
        this.pDetail.discountPrice > 0
          ? this.pDetail.discountPrice
          : this.pDetail.price;
      return this.counter > 0
        ? `${price} ☓ ${this.counter} 件 = ${price * this.counter} 元`
        : "0元";
    }
  },
  setup() {
    return {
      baseURL
    };
  },
  // 通过路由获取商品id
  activated() {
    !this.$route.query.productId &&
      (this.productId = this.$route.query.productId);
  },
  watch: {
    // 监听商品id的变化，请求后端获取商品数据
    productId: function() {
      this.getDetail();
    }
  },
  mounted() {
    this.productId = this.$route.query.productId;
  },
  methods: {
    handleTabChange(tab) {
      if (this.lastTab == tab) {
        return;
      }
      if (tab.name === "comment") {
        this.getComments();
      }
      this.lastTab = tab;
    },
    async getComments() {
      let resp = await commentApi.getComments({
        productId: this.productId
      });
      if (resp && resp.code == 0) {
        this.comment.list = resp.data.data;
      }
    },
    back2Top(acceleration, time) {
      acceleration = acceleration || 0.1;
      time = time || 16;
      var x1 = 0;
      var y1 = 0;
      var x2 = 0;
      var y2 = 0;
      var x3 = 0;
      var y3 = 0;
      if (document.documentElement) {
        x1 = document.documentElement.scrollLeft || 0;
        y1 = document.documentElement.scrollTop || 0;
      }
      if (document.body) {
        x2 = document.body.scrollLeft || 0;
        y2 = document.body.scrollTop || 0;
      }
      // 滚动条到页面顶部的水平距离
      var x = Math.max(x1, Math.max(x2, x3));
      // 滚动条到页面顶部的垂直距离
      var y = Math.max(y1, Math.max(y2, y3));
      // 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小
      var speed = 1 + acceleration;
      window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
      // 如果距离不为零, 继续调用迭代本函数
      if (x > 0 || y > 0) {
        window.setTimeout(() => {
          this.back2Top(acceleration, time);
        }, time);
      }
    },
    handleCurrentChange() {
      this.getComments();
    },
    async getDetail() {
      let resp = await productApi.detail({
        id: this.productId
      });
      if (resp && resp.data) {
        var { imgs, ...rest } = resp.data;
        this.imgs = imgs;
        Object.assign(this.pDetail, rest);
      }
    },
    ...mapActions({ getCartSize: "user/getCartSize" }),
    // 加入购物车
    addShoppingCart() {
      if (this.counter == 0) {
        this.$message.error("请选择需要购买的商品数量!");
        return;
      }
      this.$confirm({
        title: "提示",
        message: "确定要加入到购物车吗？",
        confirmed: async () => {
          try {
            this.saving = true;
            let resp = await cartApi.addCart({
              productId: this.productId,
              total: this.counter
            });
            this.saving = false;
            if (resp && resp.code == 0) {
              this.$message.success("您选择的产品已经成功加入到购物车!!!");
              this.$router.push({
                name: "CartRedirect",
                query: {
                  orderId: resp.data.id
                }
              });
              this.getCartSize();
            } else {
              this.$message.error("加入购物车失败!");
            }
          } catch {
            this.saving = false;
          }
        }
      });
    },
    handleSettle() {
      if (this.counter == 0) {
        this.$message.error("请选择需要购买的商品数量!");
        return;
      }
      var selection = [
        {
          productId: this.productId,
          total: this.counter
        }
      ];
      this.$router.push({
        name: "ConfirmOrder",
        query: {
          cart: false,
          selection: JSON.stringify(selection)
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
#details .page-header {
  height: 64px;
  margin-top: -20px;
  z-index: 4;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0px 5px 5px rgba(0, 0, 0, 0.07);
}

#details .page-header .title {
  width: 1225px;
  height: 64px;
  line-height: 64px;
  font-size: 18px;
  font-weight: 400;
  color: #212121;
  margin: 0 auto;
}

#details .page-header .title p {
  float: left;
}

#details .page-header .title .list {
  height: 64px;
  float: right;
}

#details .page-header .title .list li {
  float: left;
  margin-left: 20px;
}

#details .page-header .title .list li a {
  font-size: 14px;
  color: #616161;
}

#details .page-header .title .list li a:hover {
  font-size: 14px;
  color: $themeColor;
}

/* 主要内容CSS */
#details .main {
  width: 1225px;
  padding-top: 30px;
  margin: 0 auto;
}

#details .main .block {
  float: left;
  width: 560px;
}

#details .el-carousel .el-carousel__indicator .el-carousel__button {
  background-color: rgba(163, 163, 163, 0.8);
}

#details .main .content {
  float: left;
  margin-left: 25px;
  width: 640px;
}
#details .main .content .name,
.counter-label {
  height: 30px;
  line-height: 30px;
  font-size: 24px;
  font-weight: normal;
  color: #212121;
}

#details .main .content .intro {
  color: #b0b0b0;
  padding-top: 10px;
  line-height: 1.5em;
}

#details .main .content .price {
  display: block;
  font-size: 18px;
  color: $themeColor;
  border-bottom: 1px solid #e0e0e0;
  padding: 25px 0 25px;
}
#details .main .content .price .del {
  font-size: 14px;
  margin-left: 10px;
  color: #b0b0b0;
  text-decoration: line-through;
}

#details .main .content .pro-list {
  background: #f9f9fa;
  padding: 30px 60px;
  margin: 30px 0 30px;
}

#details .main .content .pro-list span {
  line-height: 30px;
  color: #616161;
}
#details .main .content .pro-list .pro-price {
  float: right;
}

#details .main .content .pro-list .pro-price-num {
  margin-left: 5px;
  font-size: 16px;
  color: $themeColor;
}

#details .main .content .pro-list .pro-price .pro-del {
  margin-left: 10px;
  text-decoration: line-through;
  color: #aaa;
}

#details .main .content .pro-list .price-sum {
  color: $themeColor;
  font-size: 24px;
  padding-top: 20px;
}

#details .main .content .button {
  height: 55px;
  margin: 10px 0 20px 0;
}

#details .main .content .button .el-button {
  float: left;
  height: 55px;
  font-size: 16px;
  color: #fff;
  border: none;
  text-align: center;
}
#details .main .content .button .shop-cart {
  width: 340px;
  background-color: rgba($themeColor, 0.8);
}

#details .main .content .button .shop-cart:hover {
  background-color: rgba($themeColor, 0.9);
}

#details .main .content .button .like {
  width: 260px;
  margin-left: 40px;
}

#details .main .content .button .like:hover {
  background-color: #757575;
}

#details .main .content .pro-policy li {
  float: left;
  margin-right: 20px;
  color: #b0b0b0;
}

.pro-storage {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.product-tabs {
  margin-top: 30px;
  margin-bottom: 30px;
}

.counter-label {
  margin-right: 20px;
}

.counter-message {
  color: #b0b0b0;
  margin-left: 100px;
}

.product-area {
  display: inline-block;
}

.desc-detail {
  margin: 20px 0;
}

.desc-empty {
  display: flex;
  height: 300px;
  justify-content: center;
  align-items: center;
  color: #666;
}

.comment-area {
  margin-top: 20px;

  .comment-item {
    display: flex;
    padding: 20px 0;
    border-bottom: 1px solid #ccc;
    .comment-user {
      width: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;
      &--avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
      &--username {
        color: #333;
        margin-top: 10px;
      }
      margin-right: 20px;
    }
    .comment-content {
      flex: 1;
      overflow: hidden;
      &--rate {
        margin-bottom: 10px;
      }
      &--desc {
        display: block;
        line-height: 1.5em;
        color: #666;
        margin-bottom: 30px;
      }
      &--time {
        color: #b0b0b0;
        font-size: 14px;
      }
    }
  }

  .comment-pagination {
    text-align: center;
    padding: 20px 0 10px;
    .el-pagination.is-background .el-pager li:not(.disabled).active {
      background-color: $themeColor;
    }
    .el-pagination.is-background .el-pager li:not(.disabled):hover {
      color: $themeColor;
    }
  }

  .empty-comment {
    display: flex;
    height: 300px;
    justify-content: center;
    align-items: center;
    color: #666;
  }
}

.back-to-top {
  position: fixed;
  right: 50px;
  bottom: 300px;
  border-radius: 5px;
  width: 50px;
  height: 50px;
  line-height: 50px;
  color: white;
  background-color: $themeColor;
  font-size: 30px;
  text-align: center;
  cursor: pointer;
}
</style>
